package com.example.module_main

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import androidx.appcompat.app.AlertDialog

import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.setupWithNavController
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.example.lib_base.path.RouterPath
import com.example.lib_base.view.BaseActivity
import com.example.lib_common.view.event.CustomEvent
import com.example.lib_common.view.view.BaseMvvmActivity
import com.example.module_home.HomeFragment
import com.example.module_main.databinding.ActivityMainBinding
import com.example.module_message.MessageFragment
import com.example.module_mine.MineFragment
import com.example.module_notice.NoticeFragment
import com.example.module_service.ServiceFragment
import com.google.android.material.badge.BadgeDrawable
import com.google.android.material.bottomnavigation.BottomNavigationView
import dagger.hilt.android.AndroidEntryPoint

/**
 *
 */

@AndroidEntryPoint
@Route(path = RouterPath.PATH_MAIN_PAGE)
class MainActivity : BaseMvvmActivity<ActivityMainBinding>() {

    private val fragments= arrayListOf<Fragment>()

    //定义需要用户权限
    private val needUserPermission= arrayListOf(
        Manifest.permission.CAMERA,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.READ_PHONE_NUMBERS,
        Manifest.permission.ACCESS_FINE_LOCATION,
    )
    //用户没有同意的权限
    private val unGrantPermission = arrayListOf<String>()



    override fun initViews() {
        val navHostFragment =
            supportFragmentManager.findFragmentById(R.id.fragmentContainerView) as NavHostFragment
        val navController = navHostFragment.navController
        binding.bnv.setupWithNavController(navController)

        //权限
        binding.fragmentContainerView.postDelayed({
            autoRequestPermission()
        },3000)

        //2
//        supportFragmentManager.beginTransaction()
//            .replace(R.id.fragment_container , HomeFragment())
//            .commit()
//        binding.bnv.setOnItemSelectedListener{item ->
//            when(item.itemId){
//                R.id.homeFragment ->{
//                    replaceFragment(HomeFragment())
//                    true
//                }
//                R.id.serviceFragment ->{
//                    replaceFragment(ServiceFragment())////////
//                    true
//                }
//                R.id.messageFragment ->{
//                    replaceFragment(MessageFragment())
//                    true
//                }
//                R.id.noticeFragment ->{
//                    replaceFragment(NoticeFragment())
//                    true
//                }
//                R.id.mineFragment ->{
//                    replaceFragment(MineFragment())
//                    true
//                }
//                else ->{
//                    false
//                }
//            }
//        }
    }

    override fun getActivityState(state: Bundle) {

    }

    override fun saveActivityState(outState: Bundle) {

    }

    override fun getLayoutId(): Int=R.layout.activity_main

//    private fun replaceFragment(fragment: Fragment){
//        supportFragmentManager.beginTransaction()
//            .replace(R.id.fragment_container , fragment)
//            .commit()
//    }

    /**
     * 使用RxPermission发起用户权限授权
     */
    private fun autoRequestRxPermission(){

    }



    private fun autoRequestPermission():Boolean{
        //判断系统版本，只有在6.0以后才需要动态权限
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){

            //清理一下未授权的用户权限
            unGrantPermission.clear()

            //查找还未授权的用户权限
            needUserPermission.forEach {
                var permissionState = checkSelfPermission(it)
                if (permissionState==PackageManager.PERMISSION_DENIED){//未授权
                    unGrantPermission.add(it)
                }
            }
            //发起授权
            if (unGrantPermission.size>0){
                requestPermissions(unGrantPermission.toTypedArray(),102)
                return false
            }
        }
        return true
    }

    /**
     * 权限授权返回
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        var hasUnGranted =false
        if (requestCode==102 && Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            unGrantPermission.forEach {
                //判断用户取消的权限
                if (checkSelfPermission(it)==PackageManager.PERMISSION_GRANTED){
                    hasUnGranted=true
                }
            }
        }
        //弹窗告诉用户去设置的应用详情里设置
        if (hasUnGranted){
            val builder = AlertDialog.Builder(this@MainActivity).apply {
                setTitle("权限提示")
                setMessage("没有授权，请到应用详情设置")
                setPositiveButton("去设置"){dialog,which->
                    dialog.dismiss()
                    hasUnGranted=false
                    openSettingsAppDetail()
                }
                setNeutralButton("取消"){dialog,which->
                    dialog.dismiss()
                    hasUnGranted=false
                }
            }
            builder.show()

        }
    }
    private fun openSettingsAppDetail(){
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        intent.data=Uri.fromParts("package",packageName,null)
        this@MainActivity.startActivity(intent)
    }

    /**
     * 处理其他业务发送过来的事件
     */
    override fun handEvent(event: CustomEvent) {
        super.handEvent(event)
        when(event.type){
            //有新的消息
            100->{

            }
            //有新的公告
            101->{

            }
        }
    }
}